package com.jy.modules.cims.deal.controller;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import com.jy.modules.cims.common.CimsConstant;
import com.jy.modules.cims.common.controller.CimsBaseController;
import com.jy.modules.cims.common.sysUtils.CollectionsUtils;
import com.jy.modules.cims.common.sysUtils.DateTimeUtils;
import com.jy.modules.cims.common.sysUtils.SearchParamUtil;
import com.jy.modules.cims.contract.service.ContractService;
import com.jy.modules.cims.creditright.service.CreditDealImportCheckService;
import com.jy.modules.cims.creditright.service.CreditDealService;
import com.jy.modules.cims.creditright.service.SettleCreditService;
import com.jy.modules.cims.data.common.dto.TCMmCostPlanDTO;
import com.jy.modules.cims.data.dto.ContractAllDto;
import com.jy.modules.cims.data.dto.CreditDetailDto;
import com.jy.modules.cims.data.dto.CreditRightDto;
import com.jy.modules.cims.data.dto.DealDto;
import com.jy.modules.cims.data.dto.credit.CreditApplyDto;
import com.jy.modules.cims.deal.service.DealService;
import com.jy.platform.core.message.DataMsg;
import com.jy.platform.core.message.PageParameter;
import com.jy.platform.core.message.PageUtil;
import com.jy.platform.core.message.QueryReqBean;
import com.jy.platform.restservice.exception.AbaboonException;
/**
 * 
 * ClassName: CreditDealController 
 * @Description: 债权受让控制层
 * @author dell
 * @date 2015-7-20
 */@Controller
 @Scope("prototype")
 @RequestMapping("/creditDealController")
public class CreditDealController extends CimsBaseController{
	private static final Logger logger =  LoggerFactory.getLogger(CreditDealController.class);
	public static final String DEFAULT_DATE_FORMAT = "yyyy-MM-dd";
	
	@Autowired
    @Qualifier("com.jy.modules.cims.contract.service.ContractService")
    private ContractService serviceContract;
	@Autowired
    @Qualifier("com.jy.modules.cims.creditright.service.CreditDealService")
	private CreditDealService creditDealService;
	
	@Autowired
	@Qualifier("com.jy.modules.cims.deal.service.DealService")
	public DealService dealService;

	@Autowired
	@Qualifier("com.jy.modules.cims.creditright.service.SettleCreditService")
	private SettleCreditService settleCreditService;

	@Autowired
	@Qualifier("com.jy.modules.cims.contract.service.ContractService")
	private ContractService contractService;

	@Autowired
	@Qualifier("com.jy.modules.cims.creditright.service.CreditDealImportCheckService")
	private CreditDealImportCheckService creditDealImportCheckService;
	
	@RequestMapping(value="/prepareExecute/{operate}")
	public ModelAndView execute(@PathVariable("operate") String operate) throws AbaboonException {
		ModelAndView model = new ModelAndView();
		
		if("toQuery".equals(operate)){//跳转到查询页面
			model.setViewName("cims/transfereeDeal/queryTransfereeDeal");
		}else if("toAdd".equals(operate)){//跳转到新增页面-【
			model.setViewName("cims/transfereeDeal/addTransfereeDeal");
		}else if("toBackTransfereeDealAdd".equals(operate)){ //合约确定-跳转至债权受让新增页面
        	String contractCode = this.getParameterString("contractCode");
        	model = serviceContract.queryAllDTO(contractCode);
        	model.setViewName("cims/transfereeDeal/addTransfereeDeal");
        }else if("toBackTransfereeDealUpdate".equals(operate)){//修改操作-跳转至债权受让修改页面
        	String cooperorgCode = this.getParameterString("cooperorgCode");
        	String contractCode = this.getParameterString("contractCode");
        	String dealCode = this.getParameterString("dealCode");
        	String idDeal = this.getParameterString("idDeal");
        	model = serviceContract.queryAllDTO(cooperorgCode,contractCode,dealCode);
        	model.addObject("idDeal", idDeal);
        	model.setViewName("cims/transfereeDeal/updateTransfereeDeal");
        }else if("toView".equals(operate)){
        	String cooperorgCode = this.getParameterString("cooperorgCode");
        	String contractCode = this.getParameterString("contractCode");
        	String dealCode = this.getParameterString("dealCode");
        	model = serviceContract.queryAllDTO(cooperorgCode,contractCode,dealCode);
			model.setViewName("cims/transfereeDeal/viewCreditTransferee");
        }
		return model;
	}
	
	
	/**
	 * 
	 * @Description  导入excel
	 * @param request
	 * @param dto
	 * @param dataMsg
	 * @return   
	 * DataMsg  
	 * @throws
	 * @author zhangmi
	 * @date 2015-7-22
	 */
	@SuppressWarnings("unchecked")
	@RequestMapping(value = "/doTransfereeDeal")
	@ResponseBody
	public DataMsg doTransfereeDeal(HttpServletRequest request,HttpServletResponse response,CreditApplyDto dto, @ModelAttribute DataMsg dataMsg) throws Exception{
		try {
			String dataType = dto.getDataType() == null ? "" : dto.getDataType().trim();
			List<CreditDetailDto> creditDetailList = new ArrayList<CreditDetailDto>();
			if (CimsConstant.SESSION_IMPORT_DATA_PATH.equals(dataType)) {
				creditDetailList = (List<CreditDetailDto>) request.getSession().getAttribute(dto.getDataId());
			} 
			//检验excel数据
			creditDealImportCheckService.doImportCheck(creditDetailList,dto);
			dto.setCreditDetailList(creditDetailList);
			creditDealService.doTransferee(dto);
			
			dataMsg.setData(dto);
			dataMsg.setStatus("ok");
			dataMsg.setMsg("调用creditDealService.doTransferee成功！");
		} catch (Exception e) {
			dataMsg.setStatus("error");
			dataMsg.setMsg(e.getMessage());
			request.getSession().removeAttribute(dto.getDataId());//从session中移除数据
			logger.error("执行方法creditDealService.doTransferee异常：", e);
			
		}
		return dataMsg;
	}
	
	/**
	 * 
	 * @Description 完成受让操作
	 * @param request
	 * @param dataMsg
	 * @return   
	 * DataMsg  
	 * @throws
	 * @author zhangmi
	 * @date 2015-7-23
	 */
	@RequestMapping(value = "/saveTransFereeDeal")
	@ResponseBody
	public DataMsg saveTransFereeDeal(HttpServletRequest request, @ModelAttribute DataMsg dataMsg) {
		super.initDto(null);
		String dealCode = (String) this.getParameter("dealCode");// 格式: 1,2,3
		dataMsg = super.initDataMsg(dataMsg);
		try {
			creditDealService.doSendApply(dealCode);
			dataMsg.setMsg("完成成功！");
		} catch (Exception e) {
			dataMsg.failed(e.getMessage());
			dataMsg.setMsg(e.getMessage());
			logger.error("执行方法tCMmTransfereeDeal/deleteDeal异常：", e);
		}
		return dataMsg;
	}
	
	/**
	 * 
	 * @Description 交易流水号删除操作-受让
	 * @param request
	 * @param dataMsg
	 * @return   
	 * DataMsg  
	 * @throws
	 * @author zhangmi
	 * @date 2015-7-21
	 */
	@RequestMapping(value = "/deleteDeal")
	@ResponseBody
	public DataMsg deleteDeal(HttpServletRequest request, @ModelAttribute DataMsg dataMsg) {
		super.initDto(null);
		String dealCodes = (String) this.getParameter("dealCodes");// 格式: 1,2,3
		dataMsg = super.initDataMsg(dataMsg);
		try {
			String [] arrayDealCodes = dealCodes.split(",");
			List<CreditApplyDto> applyDtoList = new ArrayList<CreditApplyDto>();
			for (int i = 0; i < arrayDealCodes.length; i++) {
				CreditApplyDto dto = new CreditApplyDto();
				dto.setDealCode(arrayDealCodes[i].trim());
				applyDtoList.add(dto);
			}
			creditDealService.doCancelApply(applyDtoList);
			dataMsg.setMsg("删除成功！");
		} catch (Exception e) {
			dataMsg.failed(e.getMessage());
			dataMsg.setMsg("删除失败！"+e.getMessage());
			logger.error("执行方法creditDealController/deleteDeal异常：", e);
			//throw new CimsException(e.getMessage());
		}
		return dataMsg;
	}
	
	/**
	 * 
	 * @Description 根据交易流水号查询交易流水信息  --
	 * @param dealCode
	 * @throws AbaboonException   
	 * ModelAndView  
	 */
	@SuppressWarnings("unused")
	private ModelAndView queryOneDTO(String dealCode) throws AbaboonException {
		ModelAndView model = new ModelAndView();
		try {
			CreditRightDto creditRightDto = null;
			Map<String, Object> searchParams = new HashMap<String, Object>();
			DealDto dealDto = new DealDto();
			dealDto.setDealCode(dealCode);
			searchParams.put("dto", dealDto);
			QueryReqBean params = new QueryReqBean();
			params.setSearchParams(searchParams);
			PageParameter pageInfo = PageUtil.toPageParameter(new DataMsg());
			params.setPageParameter(pageInfo);
			List<DealDto> dealDtoList = dealService.getDealList(params.getSearchParams());

			if (CollectionsUtils.isNotEmpty(dealDtoList)) {
				dealDto = dealDtoList.get(0);
				/* 查询合约信息 */
				ContractAllDto contractAllDto = contractService.getContractAllInfo(dealDto.getContractCode());
				model.addObject("contractAllDto", contractAllDto);
				model.addObject("dealCode", dealDto.getDealCode());

				creditRightDto = dealService.getDealDetailByCreditListByTotal(SearchParamUtil.getSearchParam(dealDto));
			}

			List<TCMmCostPlanDTO> costPlanList = settleCreditService.searchCostPlanByDealCode(dealCode);
			if (CollectionsUtils.isNotEmpty(costPlanList)) {
				TCMmCostPlanDTO costPlanPlanDto = costPlanList.get(0);
				model.addObject("costPlanPlanDto", costPlanPlanDto);
				model.addObject("settleDate", DateTimeUtils.formatDate(costPlanPlanDto.getStartDate(), DEFAULT_DATE_FORMAT));
			}else{
				model.addObject("settleDate", DateTimeUtils.formatDate(dealDtoList.get(0).getSettleDate(), DEFAULT_DATE_FORMAT));
			}

			model.addObject("dealDto", dealDtoList == null ? null : dealDtoList.get(0));
			model.addObject("creditRightDto", creditRightDto);

		} catch (Exception e) {
			throw new AbaboonException("执行queryOneDTO异常：", e);
		}
		return model;
	}
	
	/**
	 * 
	 * @Description 新增债权受让操作未保存，关闭删除数据
	 * @param request
	 * @param dataMsg
	 * @return
	 * @throws Exception   
	 * DataMsg  
	 * @throws
	 * @author zhangmi
	 * @date 2015-7-21
	 */
	@RequestMapping(value="/closeDeleteDealAndCredit")
	@ResponseBody
	public DataMsg closeDeleteDealAndCredit(HttpServletRequest request,@ModelAttribute DataMsg dataMsg)throws Exception{
		try {
			//String dealCode = this.getParameterString("dealCode");
			//transfereeDealService.closeRemoveDealAndCredit(dealCode);
		} catch (Exception e) {
			dataMsg.failed(e.getMessage());
			logger.error("执行方法closeDeleteDealAndCredit异常：", e);
			throw new Exception(e.getMessage());
		}
		return dataMsg;
	}
		
	/**
	 * 实时更新核心日终状态
	 * @param request
	 * @param dataMsg
	 * @return
	 * @throws Exception   
	 * DataMsg  
	 * @throws
	 * @author zhangmi
	 * @date 2016-3-10
	 */
	@RequestMapping(value="/realTimeUpdateSettleResult")
	@ResponseBody
	public DataMsg realTimeUpdateSettleResult(HttpServletRequest request,@ModelAttribute DataMsg dataMsg)throws Exception{
		try {
//			creditDealService.updateSettleResult();
			creditDealService.settleResult();
			dataMsg.setStatus("ok");
			dataMsg.setMsg("执行完毕！");
		} catch (Exception e) {
			dataMsg.failed(e.getMessage());
			logger.error("执行方法realTimeUpdateSettleResult异常：", e);
			dataMsg.setStatus("no");
			dataMsg.setMsg(e.getMessage());
		}
		return dataMsg;
	}
		
}
